<template>
  <div class="expanding-cards">
    <div
      @mouseenter="mouseenter(index)"
      @mouseleave="mouseleave(index)"
      @click="selecrIndex = index"
      v-for="(item, index) in imgs"
      :key="item"
      :class="selecrIndex === index ? 'active' : ''"
      class="card-img"
      :style="{ backgroundImage: `url(${item})` }"
    ></div>
  </div>
</template>

<script>
export default {
  data() {
    const imgs = [
      require("./image/img1.webp"),
      require("./image/img2.webp"),
      require("./image/img3.webp"),
      require("./image/img4.webp"),
      require("./image/img5.webp"),
    ];
    return {
      selecrIndex: 4,
      imgs,
      length: imgs.length - 1,
      imgsTimer: null,
    };
  },
  methods: {
    loopPlayback() {
      this.imgsTimer = setInterval(() => {
        if (this.selecrIndex < this.length) {
          this.selecrIndex += 1;
        } else {
          this.selecrIndex = 0;
        }
      }, 3000);
    },
    stopLoop() {
      clearInterval(this.imgsTimer);
      this.imgsTimer = null;
    },
    mouseenter() {
      this.stopLoop();
    },
    mouseleave() {
      this.loopPlayback();
    },
  },
  mounted() {
    this.loopPlayback();
  },
  beforeDestroy() {
    this.stopLoop();
  },
};
</script>

<style scoped lang="scss">
.expanding-cards {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  .card-img {
    width: 100%;
    background-position: center;
    background-repeat: no-repeat;
    height: 50vh;
    background-size: cover;
    flex: 0.5;
    border-radius: 50px;
    margin: 0 20px;
    transition: flex 0.5s;
    cursor: pointer;
    &.active {
      flex: 5;
    }
  }
}
</style>
